//
//  FDBMBase.m
//  FMDBSelf
//
//  Created by Cheng on 15/12/26.
//  Copyright © 2015年 Cheng. All rights reserved.
//

#import "CGFdbmBase.h"
#import "FMDatabase.h"
static FMDatabase *_database;

@implementation CGFdbmBase
//建表
+(void)CreatTableWhithPath:(NSString *)PathName TableName:(NSString *)tableName DicName:(NSString *)Dic IdstrName:(NSString *)idStrName{
    [CGFdbmBase OpenSQlWhiPathName:PathName];
    NSString *SQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id integer PRIMARY KEY,%@ text NOT NULL,%@ blob NOT NULL)",tableName,idStrName,Dic];
    
    /**
     *  先判断是否存在改表
     */
    if (![CGFdbmBase isTableOK:tableName]) {
        
        //判断是否创建成功
        if ([_database executeStatements:SQL]) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"Error: %@",_database.lastErrorMessage);
        }

    }

   
}

#pragma mark--打开数据库
+(void)OpenSQlWhiPathName:(NSString *)PathName{
    
    
    /*在真机上没问题*/
    NSString *path  = [NSString stringWithFormat:@"%@/Library/Caches/Data.db",NSHomeDirectory()];

    _database  = [FMDatabase databaseWithPath:path];
    
    if (![_database open]) {
        NSLog(@"Open failed");
    }

}

#pragma mark----判断是否存在表
+ (BOOL) isTableOK:(NSString *)tableName
{
    FMResultSet *rs = [_database executeQuery:@"SELECT count(*) as 'count' FROM sqlite_master WHERE type ='table' and name = ?", tableName];
    while ([rs next])
    {
        NSInteger count = [rs intForColumn:@"count"];
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}

#pragma mark---获取数据条数
+ (NSInteger) getTableItemCount:(NSString *)tableName
{
    NSString *sqlstr = [NSString stringWithFormat:@"SELECT count(*) as 'count' FROM %@", tableName];
    FMResultSet *rs = [_database executeQuery:sqlstr];
    NSInteger count = 0;
    while ([rs next])
    {
        
       count = [rs intForColumn:@"count"];
       
      
    }
    return count;
}

#pragma mark---插入数据
+(void)IntoDicTableName:(NSString *)tableName DicName:(NSString *)DicName IdstrName:(NSString *)idStrName Dic:(NSDictionary *)dic idStr:(NSString *)idStr {
    
    NSString *insertSQL2 =[NSString stringWithFormat:@"INSERT INTO %@ (%@,%@) VALUES(?,?)",tableName,idStrName,DicName];
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    
   
    if ([_database executeUpdate:insertSQL2,idStr,data]) {
//        NSLog(@"加入成功");
        
    }else{
        NSLog(@"---%@",_database.lastErrorMessage);
    }
   
}

#pragma mark---搜索
+(NSString *)SeachWhithTableName:(NSString *)tableName IdStrName:(NSString *)idStrName{

    NSString *querySQL =[NSString stringWithFormat: @"SELECT * FROM %@",tableName];
    
    FMResultSet *rs = [_database executeQuery:querySQL];
    
    NSString *seach;
    
    while ([rs next]) {
        
        if ([rs stringForColumn:idStrName]) {
            seach = [rs stringForColumn:idStrName];
           
        }else{
           seach = @"没有找到";
        }
    }
    
    return seach;
    
}

#pragma mark---获取数据库数据
+(NSArray *)ListWhith:(NSString *)table dicName:(NSString *)dicName{
    
    NSString *querySQL = [NSString stringWithFormat:@"SELECT * FROM %@",table];
    
    FMResultSet *set = [_database executeQuery:querySQL];
    NSMutableArray *list = [NSMutableArray array];
    
    while (set.next) {
        // 获得当前所指向的数据
        NSData *data = [set objectForColumnName:dicName];
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [list addObject:dic];
    }

    return list;

}
#pragma mark--清空表格
+(BOOL) eraseTable:(NSString *)tableName
{
    NSString *sqlstr = [NSString stringWithFormat:@"DELETE FROM %@", tableName];
    if (![_database executeUpdate:sqlstr])
    {
        
        return NO;
    }
    
    return YES;
}


#pragma mark---删除数据
+(BOOL)DeleteDtaWhiTable:(NSString *)table IdStrName:(NSString *)idStrName idStr:(NSString *)idStr {
    
    /*第一个参数为表名  第二个为字段名  第三个为要删除的参数*/
    NSString *delete = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",table,idStrName];
    
    if( [_database executeUpdate:delete,idStr]){
        return YES;
        
    }else{
        return NO;
    }
}
#pragma mark---跟新替换
+(BOOL)UPDataWhiTable:(NSString *)table IdStrName:(NSString *)idStrName idStr:(NSString *)idStr SetIdStr:(NSString *)SetidStr {

     NSString *update = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ? WHERE %@ = ? ",table,idStrName,idStrName];
    
    if ([_database executeUpdate:update,SetidStr,idStrName]) {
        return YES;
    }else{
        return NO;
        
    }
}



/**
 *  查询本地 数据库数据
 */
+(NSMutableArray *)SearchSelfPathSqlWhithPath:(NSString *)SQLpath AndTabName:(NSString *)tabName SelectSting:(NSString *)string{

  
    NSString *dbPath = [[NSBundle mainBundle]pathForResource:SQLpath ofType:@"db"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path.firstObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",SQLpath]];
    
    [manager copyItemAtPath:dbPath toPath:documentPath error:nil];
    
    FMDatabase *dbDatabase = [FMDatabase databaseWithPath:documentPath];
    
    [dbDatabase open];
    NSString *quer = string;
    
    NSMutableArray *resultAry = [NSMutableArray array];
 
    [dbDatabase executeStatements:quer withResultBlock:^int(NSDictionary *resultsDictionary) {
        
        [resultAry addObject:resultsDictionary];

        return 0;
    }];
  
    
    [dbDatabase close];

    return resultAry;
}

#pragma mark---搜索
+(NSArray *)SeachWhithPath:(NSString *)SQLpath AndTableName:(NSString *)tableName IdStrName:(NSString *)idStrName{
    
    
    NSString *dbPath = [[NSBundle mainBundle]pathForResource:SQLpath ofType:@"db"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path.firstObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",SQLpath]];
    
    [manager copyItemAtPath:dbPath toPath:documentPath error:nil];
    
    FMDatabase *dbDatabase = [FMDatabase databaseWithPath:documentPath];
    
    [dbDatabase open];

    
    NSString *querySQL =[NSString stringWithFormat: @"SELECT * FROM %@",tableName];
    
    FMResultSet *rs = [dbDatabase executeQuery:querySQL];
    
    NSString *seach;
    
    NSMutableArray *resultAry = [NSMutableArray array];

    
    while ([rs next]) {
        
        if ([rs stringForColumn:idStrName]) {
            seach = [rs stringForColumn:idStrName];
            
             [resultAry addObject:seach];
            
        }else{
            seach = @"没有找到";
        }
    }
    
   
    
    return [resultAry mutableCopy];
    
}


@end
